﻿using System;
using System.Web;
using System.Web.UI;

namespace TQB.Plugin.HttpHandlers
{
    /// <summary>
    /// 自定义处理程序工厂。
    /// </summary>
    /// <example>
    /// <![CDATA[
    /// <httpHandlers>
    ///     <add path="*.rss,*.atom" type="TQB.Plugin.HttpHandlers.HandlerFactory" verb="GET" />
    /// </httpHandlers>
    /// ]]>
    /// </example>
    public class HandlerFactory : IHttpHandlerFactory
    {
        #region IHttpHandlerFactory Members

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            string path = context.Request.PhysicalPath;

            if (System.IO.Path.GetExtension(path) == ".rss")
            {
                return new RSSHandler();
            }
            else if (System.IO.Path.GetExtension(path) == ".js")
            {
                return new JSHandler();
            }
            else
                return new DefaultHttpHandler();
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
            //throw new NotImplementedException();
        }

        #endregion
    }

    /// <summary>
    /// 扩展默认ASP.NET的工厂。
    /// </summary>
    public class PageHandlerFactoryExt : IHttpHandlerFactory
    {

        #region IHttpHandlerFactory Members

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            PageHandlerFactory factory = (PageHandlerFactory)Activator.CreateInstance(typeof(PageHandlerFactory), true);

            IHttpHandler handler = factory.GetHandler(context, requestType, url, pathTranslated);

            //TODO: 添加要处理的问题。


            return handler;
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
            //throw new NotImplementedException();
        }

        #endregion

        private void Excute(IHttpHandler hanlder)
        {
            if (hanlder is System.Web.UI.Page)
            {
                ((System.Web.UI.Page)hanlder).PreLoad += new EventHandler(PageHandlerFactoryExt_PreLoad);
            }
        }

        public void PageHandlerFactoryExt_PreLoad(object sender, EventArgs e)
        {
            ((System.Web.UI.Page)sender).Response.Write("CopyWrite 2010");
        }

    }

}
